package io.github.javpower.gifweb.store;

import io.github.javpower.gifweb.entity.Template;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class TemplateStore {
    private final String filePath = "template.dat";
    private final File file = new File(filePath);
    private final RandomAccessFile randomAccessFile;
    private final FileChannel fileChannel;
    private final ObjectOutputStream objectOutputStream;
    private final ObjectInputStream objectInputStream;
    private final Map<String, Template> templateMap = new HashMap<>();

    public TemplateStore() throws IOException, ClassNotFoundException {
        if (!file.exists()) {
            file.createNewFile();
        }
        randomAccessFile = new RandomAccessFile(file, "rw");
        fileChannel = randomAccessFile.getChannel();
        objectOutputStream = new ObjectOutputStream(new FileOutputStream(file, file.length() > 0));
        objectInputStream = new ObjectInputStream(new FileInputStream(file));
        loadTemplates();
    }

    public void saveTemplate(Template template) throws IOException {
        templateMap.put(template.getTemplateId(), template);
        objectOutputStream.reset(); // 重置输出流，避免重复写入
        objectOutputStream.writeObject(templateMap);
        objectOutputStream.flush();
    }

    public Template getTemplate(String templateId) {
        return templateMap.get(templateId);
    }

    public void deleteTemplate(String templateId) throws IOException {
        templateMap.remove(templateId);
        objectOutputStream.reset(); // 重置输出流，避免重复写入
        objectOutputStream.writeObject(templateMap);
        objectOutputStream.flush();
    }

    public Map<String, Template> getAllTemplates() {
        return new HashMap<>(templateMap);
    }

    private void loadTemplates() throws IOException, ClassNotFoundException {
        if (file.length() > 0) {
            try {
                templateMap.clear();
                templateMap.putAll((Map<String, Template>) objectInputStream.readObject());
            } catch (EOFException e) {
                // 文件为空或损坏，初始化一个新的空映射
                templateMap.clear();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() throws IOException {
        objectOutputStream.close();
        objectInputStream.close();
        fileChannel.close();
        randomAccessFile.close();
    }
}